package com.wsc.springbootmultidevdemo.springMsg;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.nio.file.Files;
import java.util.UUID;

/**
 * 图片转换器
 */
public class ImageMessageConverter implements MessageConverter {
    @Override
    public Message toMessage(Object o, MessageProperties messageProperties) throws MessageConversionException {
        throw new MessageConversionException(" convert error");
    }

    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        System.err.println(" ----------- Image Message Converter ----------");

        //获取消息的扩展名
        Object _extName = message.getMessageProperties().getHeaders().get("extName");
        //如果扩展名是 null 就赋值 png 否则赋值扩展名
        String extName = _extName == null ? "png" : _extName.toString();

        byte[] body = message.getBody();
        String fileName = UUID.randomUUID().toString();
        String path = "/Users/weisicong/Downloads/"+fileName+"."+extName;
        File file = new File(path);
        try {//将消息复制并写入到指定路径
            Files.copy(new ByteArrayInputStream(body), file.toPath());
        } catch (Exception e){
            e.printStackTrace();
        }
        return file;
    }
}
